# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : mapReduce聚合操作.py
# @Author: dongguangwen
# @Date  : 2025-06-15 16:41
# pip install pymongo==3.12.3  4.0+版本不支持
from pymongo import MongoClient

client = MongoClient('mongodb://root:root123@192.168.1.119:27017/')
db = client['learning_mongodb']
collection = db['users']

# 定义 map 函数（JavaScript）
mapper = """
function () {
    emit(this.address.city, 1);
}
"""

# 定义 reduce 函数（JavaScript）
reducer = """
function (key, values) {
    return Array.sum(values);
}
"""

# 执行 MapReduce
result = collection.map_reduce(
    mapper,
    reducer,
    out="city_user_count"
)

# 查询输出结果
print("各城市用户数量：")
for doc in result.find():
    print(doc)
    print(f"{doc['_id']}: {doc['value']}")

"""
各城市用户数量：
{'_id': 'Beijing', 'value': 2.0}
Beijing: 2.0
{'_id': 'Shenzhen', 'value': 5.0}
Shenzhen: 5.0
{'_id': 'Shanghai', 'value': 1.0}
Shanghai: 1.0
{'_id': 'Guangzhou', 'value': 2.0}
Guangzhou: 2.0
"""